package vell.velllock.activity;

import java.io.IOException;

import vell.velllock.R;
import vell.velllock.R.layout;
import vell.velllock.database.WordDBUtil;
import vell.velllock.service.MyLockScreenService;
import vell.velllock.util.VellLockUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements SensorEventListener {
	private SensorManager mSensorManager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try {
			WordDBUtil.refreshWordDB(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		VellLockUtil.startService(getBaseContext(), MyLockScreenService.class);
		VellLockUtil.startActivity(getBaseContext(), VellLock.class);
		// Sensor
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// accelerometer sensor
		mSensorManager.registerListener(this,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
		// also have SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME etc.
	}

	@Override
	protected void onStop() {
		mSensorManager.unregisterListener(this);
		super.onStop();
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(this);
		super.onPause();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO nothing
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();

		// values[0]: X Axis, values[1]: Y Axis, values[2]: Z Axis
		float[] values = event.values;

		if (sensorType == Sensor.TYPE_ACCELEROMETER) {
			// Axis' value is smaller than 14 Under normal circumstances
			if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14)) {
				VellLockUtil.startActivity(getBaseContext(), VellLock.class);
			}
		}
	}
}